# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        n1 = 1
        head1 = ListNode(0, head)
        flag1 = head1
        flag2 = head.next
        while flag2:
            if n1 < n:
                n1 += 1
                flag2 = flag2.next
            else:
                flag1 = flag1.next
                flag2 = flag2.next
        flag3 = flag1.next
        if flag1 == head and flag3 == None:
            return None
        # print(flag1.val)
        if flag3.next == None:
            flag1.next = None
        else:
            flag3 = flag3.next
            flag1.next = flag3
        head2 = head1.next
        return head2


node5 = ListNode(5)
node4 = ListNode(4, node5)
node3 = ListNode(3, node4)
# node2 = ListNode(2, node3)
# node1 = ListNode(1, node2)

lll = Solution()

lll3 = lll.removeNthFromEnd(node3, 3)

while lll3:
    print(lll3.val)
    lll3 = lll3.next
